//
//  CZPictureView.swift
//  weibo
//
//  Created by 丁蒙 on 16/6/30.
//  Copyright © 2016年 丁蒙. All rights reserved.
//

import UIKit

//重用标识
private let pictureViewCellId: String = "pictureViewCellId"
//cell之间的距离
private let itemMargin: CGFloat = 5
//cell的宽高
private let cellWH = (SCREENW - 2 * statusMargin - itemMargin * 2) / 3


class CZPictureView: UICollectionView {
    
    var count: Int = 0
    
    var pic_urls: [CZPictureInfo]? {
        didSet {
            count = pic_urls?.count ?? 0
            let pictureViewSize = getPictureViewSize(count)
            
            self.snp_updateConstraints { (make) in
                make.size.equalTo(pictureViewSize)
            }
            //刷新数据
            reloadData()
        }
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /**
     设置视图
     */
    private func setupUI() {
        self.backgroundColor = UIColor.whiteColor()
        //注册
        registerClass(CZPictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellId)
        //设置代理
        dataSource = self
        delegate = self
        //计算item大小
        let layOut = collectionViewLayout as! UICollectionViewFlowLayout
        layOut.itemSize = CGSize(width: cellWH, height: cellWH)
        layOut.minimumLineSpacing = itemMargin
        layOut.minimumInteritemSpacing = itemMargin
        
    }
    //计算自身的size
    private func getPictureViewSize(count: Int)-> CGSize {
        let col = count == 4 ? 2 : (count >= 3 ? 3 : count)
        let row = count == 4 ? 2 : ((count - 1) / 3 + 1)
        //配图的size
        let W = CGFloat(col) * cellWH + CGFloat(col - 1) * itemMargin
        let H = CGFloat(row) * cellWH + CGFloat(row - 1) * itemMargin
        
        return CGSize(width: W, height: H)
        
    }

}

extension CZPictureView:UICollectionViewDataSource ,UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellId, forIndexPath: indexPath) as! CZPictureViewCell

        cell.pictureInfo = pic_urls?[indexPath.item]
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        
        photoBrowser.delegate = self
        
        photoBrowser.currentImageIndex = indexPath.item

        photoBrowser.imageCount = pic_urls!.count

        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.show()

    }
}
extension CZPictureView: SDPhotoBrowserDelegate {
    // 返回临时占位图片（即原来的小图）
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
        let cell = cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! CZPictureViewCell
        
        return cell.cellImageView.image
    }
    // 返回高质量图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let urlStr = pic_urls![index].thumbnail_pic ?? ""
        
        return NSURL(string: urlStr)
    }
}
// MARK - 自定义cell
class CZPictureViewCell: UICollectionViewCell {
    
    var pictureInfo: CZPictureInfo? {
        didSet {
    
            let url = NSURL(string: pictureInfo?.thumbnail_pic ?? "")
            
            cellImageView.sd_setImageWithURL(url!, placeholderImage: UIImage(named: "timeline_card_top_background"))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(cellImageView)
        
        cellImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
    }
    
    // MARK - 懒加载控件
    private lazy var cellImageView: UIImageView = {
       let imag = UIImageView()
        //设置图片填充方式
        imag.contentMode = .ScaleToFill
        imag.clipsToBounds = true
        
        return imag
    }()
}











